package com.wjc.business.controller.admin.web;


import com.alibaba.fastjson.JSONObject;
import com.wjc.business.BusinessApplication;
import com.wjc.server.dto.*;
import com.wjc.server.enums.SmsUseEnum;
import com.wjc.server.exception.BusinessException;
import com.wjc.server.service.MemberService;
import com.wjc.server.service.SmsService;
import com.wjc.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;


@RestController("webMemberController")
@RequestMapping("/web/member")
public class MemberController {

    private static final Logger LOG= LoggerFactory.getLogger(BusinessApplication.class);
    public static final String BUSINESS_NAME = "会员";

    @Resource
    private MemberService memberService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private SmsService smsService;

    //查询
    @GetMapping("/list")
    public CommonDto list(@Valid  PageDto pageDto){
         memberService.list(pageDto);
//         LOG.info("分页有啥: {}",pageDto);
        CommonDto<PageDto> pageDtoCommonDto = new CommonDto<>();
        pageDtoCommonDto.setContent(pageDto);
        return pageDtoCommonDto;
    }

    //保存
    @PostMapping("/save")
    public CommonDto list(@Valid @RequestBody MemberDto memberDto){
        CommonDto commonDto=new CommonDto<>();
        memberService.save(memberDto);
        return commonDto;

    }

    //删除
    @DeleteMapping("/delete/{id}")
    public CommonDto delete(@PathVariable Long id){
        CommonDto commonDto=new CommonDto<>();
        memberService.delete(id);
        return commonDto;
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @PostMapping("/register")
    public CommonDto register(@RequestBody MemberDto memberDto) {

        // 密码加密
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));

        // 校验短信验证码
        SmsDto smsDto = new SmsDto();
        smsDto.setMobile(memberDto.getMobile());
        smsDto.setCode(memberDto.getSmsCode());
        smsDto.setUse(SmsUseEnum.REGISTER.getCode());
        smsService.validCode(smsDto);
        LOG.info("短信验证码校验通过");

        CommonDto responseDto = new CommonDto();
        memberService.save(memberDto);
        responseDto.setContent(memberDto);
        return responseDto;
    }

    //登录
    @PostMapping("/login")
    public CommonDto login(@Valid @RequestBody MemberDto memberDto){
        CommonDto commonDto=new CommonDto<>();

        //根据验证码token去获取缓存中的验证码对比用户输入的验证码是否一致
        //String imageCode= (String) request.getSession().getAttribute(memberDto.getImageCodeToken());
        //改用redis存储
        String imageCode= (String) redisTemplate.opsForValue().get(memberDto.getImageCodeToken());

        if(StringUtils.isEmpty(imageCode)){
            //若为空则说明session过期，验证码过期
            commonDto.setSuccess(false);
            commonDto.setMessage("验证码已过期");
            LOG.info("验证码过期");
            return commonDto;
        }
        if(!imageCode.toLowerCase().equals(memberDto.getImageCode().toLowerCase())){
            //验证码错误
            commonDto.setSuccess(false);
            commonDto.setMessage("验证码错误");
            LOG.info("验证码错误");
            return commonDto;
        }else {
            //验证通过,移除验证码
//            request.getSession().removeAttribute(memberDto.getImageCodeToken());
            redisTemplate.delete(memberDto.getImageCodeToken());
        }

        //加密密码
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));
        LoginMemberDto loginmember = memberService.login(memberDto);

        //生成token
        Long token=snowFlake.nextId();
        loginmember.setToken(token.toString());
        //用户信息存入redis,有效期24小时
        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(loginmember),3600*24, TimeUnit.SECONDS);

        commonDto.setContent(loginmember);
        return commonDto;
    }

    //退出登录
    @GetMapping("/logout/{token}")
    public CommonDto logout(@PathVariable  String token){
        CommonDto commonDto=new CommonDto<>();
        //删除token
        redisTemplate.delete(token);
        return commonDto;
    }

    /**
     * 校验手机号是否存在
     * 存在则success=true，不存在则success=false
     */
    @GetMapping("/is-mobile-exist/{mobile}")
    public CommonDto isMobileExist(@PathVariable(value = "mobile") String mobile) throws BusinessException {
        LOG.info("查询手机号是否存在开始");
        CommonDto responseDto = new CommonDto();
        MemberDto memberDto = memberService.findByMobile(mobile);
        if (memberDto == null) {
            responseDto.setSuccess(false);
        } else {
            responseDto.setSuccess(true);
        }
        return responseDto;
    }

    @PostMapping("/reset-password")
    public CommonDto resetPassword(@RequestBody MemberDto memberDto) throws BusinessException {
        LOG.info("会员密码重置开始:");
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));
        CommonDto<MemberDto> responseDto = new CommonDto();

        // 校验短信验证码
        SmsDto smsDto = new SmsDto();
        smsDto.setMobile(memberDto.getMobile());
        smsDto.setCode(memberDto.getSmsCode());
        smsDto.setUse(SmsUseEnum.FORGET.getCode());
        smsService.validCode(smsDto);
        LOG.info("短信验证码校验通过");

        // 重置密码
        memberService.resetPassword(memberDto);

        return responseDto;
    }

}
